﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.IO;
using Microsoft.Practices.ServiceLocation;

namespace Dynamic_UI_Framework
{
    [Export(typeof(PartController))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class PartController
    {
        public PartController()
        {
            string path = UISetting.PartPath;
            if (Directory.Exists(path) == false)
                return;

            PartNode root = new PartNode { Path = path, IsFolder = true, ChildNodes = new List<PartNode>() };
            DoPartNode(root);
            this.Root = root;
        }

        private void DoPartNode(PartNode node)
        {
            if (node.IsFolder == false)
                return;

            string[] directories = Directory.GetDirectories(node.Path, "*", SearchOption.TopDirectoryOnly);
            foreach (var item in directories)
            {
                PartNode pn = new PartNode { Path = item, IsFolder = true, ChildNodes = new List<PartNode>() };
                DoPartNode(pn);
                node.ChildNodes.Add(pn);
            }

            string[] files = Directory.GetFiles(node.Path, "*.xaml", SearchOption.TopDirectoryOnly);
            foreach (var item in files)
            {
                node.ChildNodes.Add(new PartNode { Path = item, IsFolder = false, ChildNodes = null });
            }
        }

        public PartNode Root { get; private set; }

        public void Mapping()
        {
            if (this.Root == null)
                return;

            PartAdapterMapping partAdapterMappings = ServiceLocator.Current.GetInstance<PartAdapterMapping>();
            if (partAdapterMappings != null)
            {
                List<PartNode> nodes = GetFileNode();
                foreach (var item in nodes)
                {
                    partAdapterMappings.RegisterMapping(item.Path, ServiceLocator.Current.GetInstance<PartAdapter>());
                }
            }
        }

        private List<PartNode> GetFileNode()
        {
            List<PartNode> list = new List<PartNode>();
            DoGetFileNode(list, this.Root);
            return list;
        }

        private void DoGetFileNode(List<PartNode> list, PartNode root)
        {
            if (root.IsFolder == false)
                return;

            foreach (var item in root.ChildNodes)
            {
                if (item.IsFolder == false)
                    list.Add(item);
                else
                    DoGetFileNode(list, item);
            }
        }

        public class PartNode
        {
            public string Path { get; set; }
            public bool IsFolder { get; set; }
            public List<PartNode> ChildNodes { get; set; }
        }
    }


}
